package com.cyj.dream.admin.persistence.manager.systems;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyj.dream.admin.contacts.enums.IsDeleteEnum;
import com.cyj.dream.admin.contacts.enums.ModuleEnum;
import com.cyj.dream.core.constant.users.UserContext;
import com.cyj.dream.core.constant.users.UserInfoDTO;
import com.cyj.dream.admin.model.system.SysDepartment;
import com.cyj.dream.admin.persistence.service.ITbSysDepartmentService;
import com.cyj.dream.admin.persistence.service.ITbSysRoleModuleService;
import com.cyj.dream.admin.persistence.service.ITbSysUserRoleService;
import com.cyj.dream.admin.service.system.SysUserService;
import com.cyj.dream.admin.util.IsEmptyUtils;
import com.cyj.dream.core.constant.enums.ResultCode;
import com.cyj.dream.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description: 部门信息服务管理类
 * @BelongsProject: dream-DreamChardonnay
 * @BelongsPackage: com.dream.DreamChardonnay.persistence.manager.systems
 * @Author: ChenYongJia
 * @CreateTime: 2021-05-08 15:28
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@Component
public class SysDepartmentManager {

    @Autowired
    private ITbSysDepartmentService iTbSysDepartmentService;

    @Autowired
    private ITbSysUserRoleService iTbSysUserRoleService;

    @Autowired
    private ITbSysRoleModuleService iTbSysRoleModuleService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 根据部门对象信息查询部门菜单树
     *
     * @param sysDepartment 部门对象
     * @return java.util.List<com.dream.DreamChardonnay.model.system.SysDepartment>
     * @date 2021/5/11 9:47
     * @author ChenYongJia
     * @version 1.0
     */
    public List<SysDepartment> selectSysDepartmentTree(SysDepartment sysDepartment) {
        log.info("进入 SysDepartmentManager 根据部门对象信息查询部门菜单树方法，传入参数为：{}", JSONObject.toJSONString(sysDepartment));
        List<SysDepartment> listSysDepartment = this.selectSysDepartmentParent(ModuleEnum.MODULE_PARENT.getCode());
        listSysDepartment.stream().forEach(item -> {
            item.setChildren(this.selectSysDepartmentParent(item.getDreamId()));
        });
        return listSysDepartment;
    }

    /**
     * 根据用户查询用户角色所拥有的部门模块
     *
     * @param sysDepartment 部门对象
     * @return java.util.Map<java.lang.Long, java.util.List < com.dream.DreamChardonnay.model.system.SysDepartment>>
     * @date 2021/5/11 9:59
     * @author ChenYongJia
     * @version 1.0
     */
    public Map<Long, List<SysDepartment>> selectSysDepartmentTreeBySysUser(SysDepartment sysDepartment) {
        log.info("进入 SysDepartmentManager 根据用户查询用户所拥有的部门模块方法，传入参数为：{}", JSONObject.toJSONString(sysDepartment));
        UserInfoDTO userInfoDto = UserContext.get();

        if (!IsEmptyUtils.isEmpty(userInfoDto)) {
            //TODO 存储当前用户所在的部门模块信息（细致化需要结合判断所属部门和所拥有角色权限信息）
            Set<Long> sysDepartmentIdSet = new HashSet<>();
            sysDepartmentIdSet.add(userInfoDto.getSysUserInfoDepartmentId());

            // 根据部门id查询出部门信息
            List<SysDepartment> depList = this.selectSysDepartmentBySysDepartmentIdList(sysDepartmentIdSet);
            if (!IsEmptyUtils.isEmpty(depList)) {
                depList.stream().forEach(item -> {
                    if (item.getSysDepartmentParentId().equals(ModuleEnum.MODULE_PARENT)) {
                        // 此为根节点

                    } else {
                        // 此为子节点

                    }
                });
            } else {
                return null;
            }
        } else {
            log.error("出现错误：用户未登录或查询失败，请联系管理员进行查看！");
            throw new BizException(ResultCode.USER_TOKEN_IS_INVALID);
        }
        return null;
    }

    /**
     * 根据主键id查询系统部门信息
     *
     * @param sysDepartmentId 部门id--set集合
     * @return java.util.List<com.dream.DreamChardonnay.model.system.SysDepartment>
     * @date 2021/5/11 9:56
     * @author ChenYongJia
     * @version 1.0
     */
    public List<SysDepartment> selectSysDepartmentBySysDepartmentIdList(Set<Long> sysDepartmentId) {
        log.info("进入 SysDepartmentManager 根据主键id查询系统部门信息方法，参数为：{}", sysDepartmentId);
        return iTbSysDepartmentService.listByIds(sysDepartmentId);
    }

    /**
     * 根据主键id查询系统部门信息
     *
     * @param sysDepartmentId 部门id
     * @return com.dream.DreamChardonnay.model.system.SysDepartment
     * @date 2021/5/31 14:09
     * @author ChenYongJia
     * @version 1.0
     */
    public SysDepartment selectSysDepartmentBySysDepartmentId(Long sysDepartmentId) {
        log.info("进入 SysDepartmentManager 根据主键id查询系统部门信息方法，参数为：{}", sysDepartmentId);
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getSysDepartmentIndex, IsDeleteEnum.DIS_DELETE.getCode());
        wrapper.eq(SysDepartment::getDreamId, sysDepartmentId);
        return iTbSysDepartmentService.getOne(wrapper);
    }

    /**
     * 根据部门id查询部门信息
     *
     * @param sysDepartmentParentId 部门id
     * @return java.util.List<com.dream.DreamChardonnay.model.system.SysDepartment>
     * @date 2021/5/11 9:49
     * @author ChenYongJia
     * @version 1.0
     */
    public List<SysDepartment> selectSysDepartmentParent(Long sysDepartmentParentId) {
        log.info("进入 SysDepartmentManager 根据部门id查询部门信息方法");
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        if (sysDepartmentParentId.equals(ModuleEnum.MODULE_PARENT.getCode())) {
            // 根节点菜单信息
            wrapper.eq(SysDepartment::getSysDepartmentParentId, ModuleEnum.MODULE_PARENT);
        } else {
            wrapper.eq(SysDepartment::getSysDepartmentParentId, sysDepartmentParentId);
        }

        wrapper.eq(SysDepartment::getDelFlag, IsDeleteEnum.DIS_DELETE.getCode());

        return iTbSysDepartmentService.list(wrapper);
    }

    /**
     * 添加部门信息
     *
     * @param sysDepartment 部门对象
     * @return boolean
     * @date 2021/5/10 9:23
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean addDepartmentInfo(SysDepartment sysDepartment) {
        log.info("进入 SysDepartmentManager 添加部门信息方法，获取到的参数为：{}", JSONObject.toJSONString(sysDepartment));
        UserInfoDTO userInfoDto = UserContext.get();

        if (!IsEmptyUtils.isEmpty(userInfoDto)) {
            sysDepartment.setCreateUserId(userInfoDto.getSysUserId());
            sysDepartment.setCreateTime(LocalDateTime.now());
            sysDepartment.setDelFlag(IsDeleteEnum.DIS_DELETE.getCode());
        } else {
            throw new BizException(ResultCode.USER_NOT_LOGGED_IN);
        }

        return iTbSysDepartmentService.save(sysDepartment);
    }

    /**
     * 修改部门信息
     *
     * @param sysDepartment 部门对象
     * @return boolean
     * @date 2021/5/10 9:23
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean updateDepartmentInfo(SysDepartment sysDepartment) {
        log.info("进入 SysDepartmentManager 修改部门信息方法，获取到的参数为：{}", JSONObject.toJSONString(sysDepartment));
        UserInfoDTO userInfoDto = UserContext.get();

        if (!IsEmptyUtils.isEmpty(userInfoDto)) {
            sysDepartment.setUpdateUserId(userInfoDto.getSysUserId());
            sysDepartment.setUpdateTime(LocalDateTime.now());
        } else {
            throw new BizException(ResultCode.USER_NOT_LOGGED_IN);
        }

        return iTbSysDepartmentService.updateById(sysDepartment);
    }

    /**
     * 删除部门信息（逻辑删除）
     *
     * @param sysDepartment 部门对象
     * @return boolean
     * @date 2021/5/10 9:23
     * @author ChenYongJia
     * @version 1.0
     */
    public boolean deleteDepartmentInfo(SysDepartment sysDepartment) {
        log.info("进入 SysDepartmentManager 删除部门信息（逻辑删除）方法，获取到的参数为：{}", JSONObject.toJSONString(sysDepartment));
        UserInfoDTO userInfoDto = UserContext.get();

        if (!IsEmptyUtils.isEmpty(userInfoDto)) {
            sysDepartment.setDelFlag(1);
            sysDepartment.setUpdateTime(LocalDateTime.now());
            sysDepartment.setUpdateUserId(userInfoDto.getSysUserId());
        } else {
            throw new BizException(ResultCode.USER_NOT_LOGGED_IN);
        }

        return iTbSysDepartmentService.updateById(sysDepartment);
    }

    /**
     * 根据部门名称查询部门
     *
     * @param sysDepartmentName 部门名称
     * @return com.dream.DreamChardonnay.model.system.SysDepartment
     * @date 2021/6/9 9:52
     * @author ChenYongJia
     * @version 1.0
     */
    public SysDepartment selectSysDepartmentByName(String sysDepartmentName) {
        log.info("进入 SysDepartmentManager 根据部门id查询部门信息方法");
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getSysDepartmentName, sysDepartmentName);

        return iTbSysDepartmentService.getOne(wrapper);
    }

    /**
     * 根据部门列表
     *
     * @return java.util.List<com.dream.DreamChardonnay.model.system.SysDepartment>
     * @date 2021/6/10 15:36
     * @author ChenYongJia
     * @version 1.0
     */
    public List<SysDepartment> selectSysDepartmentList() {
        log.info("进入 SysDepartmentManager 根据部门列表方法");
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(SysDepartment::getDelFlag, IsDeleteEnum.DIS_DELETE.getCode());
        wrapper.orderByAsc(true, SysDepartment::getDreamId);

        return iTbSysDepartmentService.list(wrapper);
    }

    public static void main(String[] args) {
        System.out.println(IsDeleteEnum.DIS_DELETE.getCode());
    }

}
